package com.hb.trade.server.project.file.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.enums.DeployStatusEnum;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.file.dto.BidFileInfoDTO;
import com.hb.core.pojo.project.file.entity.BidFileInfo;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.file.manager.BidFileInfoManager;
import com.hb.trade.server.project.file.service.BidFileInfoService;
import com.hb.trade.server.project.opening.service.BidOpeningScheduleService;
import com.hb.trade.server.project.proj.service.ProjectService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.MsgUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 招标文件 前端控制器
 * </p>
 *
 * @author zhongdl
 * @since 2021-09-16
 */
@RestController
@Api(tags = "招标文件相关", value = "bidFileInfo")
public class BidFileInfoController extends MPBaseController<BidFileInfo, BidFileInfoService> {

    private final BidSectionService bidSectionService;
    private final ProjectService projectService;
    private final BidOpeningScheduleService scheduleService;

    public BidFileInfoController(BidFileInfoService service,
                                 BidSectionService bidSectionService,
                                 ProjectService projectService,
                                 BidOpeningScheduleService scheduleService) {
        super(service);
        this.bidSectionService = bidSectionService;
        this.projectService = projectService;
        this.scheduleService = scheduleService;
    }

    /**
     * 保存招标文件编辑信息
     *
     * @param bidFileInfo
     * @return
     */
    @PostMapping("/bidFileInfo/saveBidFileInfo")
    public Message<BidFileInfo> saveBidFileInfo(@RequestBody BidFileInfoDTO bidFileInfo) {
        boolean save = service.saveBidFileInfo(bidFileInfo);
        if (save) {
            BidFileInfo fileInfo = new BidFileInfo();
            fileInfo.setId(bidFileInfo.getId());
            return MsgUtil.success(fileInfo);
        }
        return MsgUtil.msg(MsgEnum.FAILURE);
    }


    /**
     * 根据项目id查询所有的招标文件
     *
     * @param projectId
     * @return
     */
    @GetMapping("/bidFileInfo/findBidFileInfoListByProjectId/{projectId}")
    public Message<?> findBidFileInfoListByProjectId(@PathVariable Long projectId) {
        List<JSONObject> jsonObjectList = service.findBidFileInfoListByProjectId(projectId);
        if (CollectionUtils.isNotEmpty(jsonObjectList)) {
            for (JSONObject jsonObject : jsonObjectList) {
                String sectionIdS = jsonObject.get("sectionIdS", String.class);
                String sectionCodeS = jsonObject.get("sectionCodeS", String.class);
                jsonObject.putOpt("sectionIdList", StringUtils.split(sectionIdS, ","));
                jsonObject.putOpt("sectionCodeList", StringUtils.split(sectionCodeS, ","));
                jsonObject.remove("sectionIdS");
                jsonObject.remove("sectionCodeS");
            }
        }
        return MsgUtil.success(jsonObjectList);
    }

    /**
     * 查询指定项目ID的招标文件列表(带分页)
     *
     * @param bidFileInfoDTO
     * @return
     * @update zhaojk
     */
    @ApiOperation(value = "下载已经购买的招标文件", notes = "下载已经购买的招标文件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目ID", dataTypeClass = String.class),
    })
    @PostMapping("/bidFileInfo/pageFilesByProjectId")
    public Message<PageResult<BidFileInfoDTO>> pageFilesByProjectId(@RequestBody BidFileInfoDTO bidFileInfoDTO) {
        Page<BidFileInfo> pages = service.pageFilesByProjectId(bidFileInfoDTO);

        PageResult<BidFileInfo> bidFileInfoPageResult = PageResult.get(pages);

        // 匹配招标文件的发布状态名称
        PageResult<BidFileInfoDTO> pageResult = bidFileInfoPageResult.transferTo(BidFileInfoDTO.class);
        List<BidFileInfoDTO> records = pageResult.getRecords();
        for (BidFileInfoDTO record : records) {
            record.setReleaseFlagName(Enums.nameOf(DeployStatusEnum.class, record.getReleaseFlag()));
        }

        return MsgUtil.success(pageResult);
    }
    /**
     *
     * @Description: 查询指定项目ID的招标文件列表(不带分页)
     * @Author: zhongdl
     * @Date:2022/1/17 9:09
     * @param bidFileInfoDTO:
     * @return: {@link ResponseDto }
     **/
    @PostMapping("/bidFileInfo/listFilesByProjectId")
    public Message<List<BidFileInfo>> listFilesByProjectId(@RequestBody BidFileInfoDTO bidFileInfoDTO) {
        List<BidFileInfo> list = service.listFilesByProjectId(bidFileInfoDTO);
        return MsgUtil.success(list);
    }

    /**
     * 查询招标文件详情
     * 获取所有与该招标文件的标段将信息返回
     *
     * @param fileId
     * @return
     * @update zhaojk
     */
    @PostMapping("/bidFileInfo/getBidFileInfo")
    public Message<BidFileInfoDTO> getBidFileInfo(Long fileId) {
        BidFileInfoDTO bidFileInfoDTO = service.getBidFileDetail(fileId);
        if (bidFileInfoDTO == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(bidFileInfoDTO);
    }

    /**
     * 发布招标文件
     * 修改发布状态
     * (该接口会验证指定的招标文件是否满足发布的条件)
     *
     * @param fileId
     * @return
     */
    @PostMapping("/bidFileInfo/deploy")
    public Message<Boolean> deploy(Long fileId) {
        BidFileInfo bidFileInfo = service.getById(fileId);
        if (bidFileInfo == null) {
            return MsgUtil.fail("数据不存在");
        }
        BidFileInfoManager fileInfoManager = bidFileInfo.to(BidFileInfoManager.class);

        // 验证招标文件是否满足发布条件
        String missMsg = fileInfoManager.canDeploy();

        if (StrUtil.isEmpty(missMsg)) {
            fileInfoManager.setReleaseFlag(DeployStatusEnum.DEPLOYED.getCode());
            fileInfoManager.buildBaseData(2);
            boolean update = service.updateById(fileInfoManager);
            // 查询关联招标文件的标段, 更新标段状态
            bidSectionService.refreshSectionStatusByFileId(fileId);

            return MsgUtil.success(update);
        }

        return MsgUtil.fail(missMsg);
    }

    /**
     * 关联标段
     *
     * @param bidFileInfoDTO
     * @return
     */
    @PostMapping("/bidFileInfo/relateSections")
    public Message<Boolean> relateSections(@RequestBody BidFileInfoDTO bidFileInfoDTO) {
        // 查询招标文件
        BidFileInfo fileInfo = service.getById(bidFileInfoDTO.getId());
        if (fileInfo == null) {
            return MsgUtil.fail("招标文件信息不存在");
        }

        // 招标文件中的标段设置
        BidFileInfoManager fileInfoManager = fileInfo.to(BidFileInfoManager.class);
        BidSection bidSection = fileInfoManager.getSectionOptions();

        List<Long> sectionIds = bidFileInfoDTO.getSectionIds();
        for (Long sectionId : sectionIds) {
            BidSection section = bidSectionService.getById(sectionId);
            if (section == null) {
                continue;
            }
            // 复制属性
            bidSection.to(section);
            // 设置招标文件ID
            section.setFileId(bidFileInfoDTO.getId());
            bidSectionService.updateById(section);
        }
        return MsgUtil.success(true);
    }


    /**
     *
     * @Description: 根据标段id获取招标文件信息
     * @Author: zhongdl
     * @Date:2022/2/17 8:53
     * @param sectionId:
     * @return: {@link Message< BidFileInfoDTO> }
     **/
    @GetMapping("/bidFileInfo/getBidFileInfoBySectionId")
    public   Message<BidFileInfoDTO> getBidFileInfoBySectionId(@RequestParam Long sectionId){
        BidSection bidSection = bidSectionService.getById(sectionId);
        if (bidSection == null || bidSection.getFileId() == null){
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        BidFileInfoDTO bidFileDetail = service.getBidFileDetail(bidSection.getFileId());
        return MsgUtil.success(bidFileDetail);
    }


    /**
     * 变更流程
     * @author tian
     * @date 2022-4-13 11:55
     * @param bidFileInfoDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.String>
     */
    @PostMapping("/bidFileInfo/changeProcess")
    public Message<String> changeProcess(@RequestBody BidFileInfoDTO bidFileInfoDTO){
        String msg = service.changeProcess(bidFileInfoDTO);
        return msg.contains("成功") ? MsgUtil.success() : MsgUtil.fail(msg);
    }


    /**
     * 查询招标项目是否已创建了流程
     * @author tian
     * @date 2022-4-19 13:35
     * @param bidFileInfoDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.Integer>
     */
    @PostMapping("/bidFileInfo/selectSimpleOrStandard")
    public Message<Integer> selectSimpleOrStandard(@RequestBody BidFileInfoDTO bidFileInfoDTO){
        Integer simpleOrStandard = service.selectSimpleOrStandard(bidFileInfoDTO);
        return MsgUtil.success(simpleOrStandard);
    }



    /**
     * 查询招标项目是否存在已发布的招标文件
     * @author tian
     * @date 2022-4-19 13:35
     * @param bidFileInfoDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.Integer>
     */
    @PostMapping("/bidFileInfo/selectReleaseFlag")
    public Message<Integer> selectReleaseFlag(@RequestBody BidFileInfoDTO bidFileInfoDTO){
        return MsgUtil.success(service.selectReleaseFlag(bidFileInfoDTO));
    }

    /**
     * @Description: 根据公告ID查询已发布的招标文件
     *
     * @author yuezheng
     * @param bidFileInfoDTO
     * @return org.fzzn.core.model.msg.Message<java.util.List<com.hb.core.pojo.project.file.dto.BidFileInfoDTO>>
     * @date 2022/6/23 14:18
     */
    @PostMapping("/bidFileInfo/findReleaseBidFileByNoticeId")
    public Message<List<BidFileInfoDTO>> findReleaseBidFileByNoticeId(@RequestBody BidFileInfoDTO bidFileInfoDTO) {
        if (bidFileInfoDTO == null || bidFileInfoDTO.getNoticeId() == null) {
            return MsgUtil.fail("缺少必要参数");
        }
        List<BidFileInfoDTO> result = this.service.selectReleaseBidFileByNoticeId(bidFileInfoDTO.getNoticeId());
        return MsgUtil.success(result);
    }

}
